package model

import (
	"common/helper"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"strconv"
	"time"
)

// MerchantLoginResp 渠道用户登录返回数据结构体
type MerchantLoginResp struct {
	Id              string `json:"id" cbor:"id"`                           // 渠道id
	Token           string `json:"token" cbor:"token"`                     // 用户token
	OperatorName    string `json:"operator_name" cbor:"operator_name"`     // 渠道名
	Date            int64  `json:"date" cbor:"date"`                       //
	WithdrawButton  string `json:"withdraw_button" db:"withdraw_button"`   // 提现权限
	AccountSecurity int    `json:"account_security" db:"account_security"` // 账号安全
	Seamo           string `json:"seamo" cbor:"seamo"`                     //
	CodeUrl         string `json:"code_url" cbor:"code_url"`               //
}

func GetMerchantList(page, pageSize int, id string, operatorName string, ctx *fasthttp.RequestCtx) (OperatorInfoData, error) {
	data := OperatorInfoData{}
	where := " 1=1"
	oderBy := "created_at"
	oderType := "desc"
	if id != "" {
		where += " and id=" + id
	}
	if operatorName != "" {
		where += " and operator_name='" + operatorName + "'"
	}

	order := oderBy + " " + oderType

	table := "tbl_operator_info"
	join := ""
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		//OperatorInfo, _ := GetOperatorInfoById(loginUser.Operator)
		//if OperatorInfo.ExtendOperator == "" {
		//	OperatorInfo.ExtendOperator = "0"
		//}
		where += " and id in(" + loginUser.Operator + ")"
	} else if loginUser.Businsess != "" {
		BusinessInfo, _ := GetBusinessInfoById(loginUser.Businsess)
		where += " and id=" + BusinessInfo.OperatorId
		//where += " and 1=2"
	}

	offset := (page - 1) * pageSize
	if page >= 1 {
		count := "select count(1) from " + table + " " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "*"
	query := "select " + field + "  from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(pageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

type ExtendOperatorInfoData struct {
	Id           int    `db:"id" json:"id"`
	OperatorName string `db:"operator_name" json:"operator_name"`
}

func GetExtendMerchant(id int) ([]ExtendOperatorInfoData, error) {

	data := []ExtendOperatorInfoData{}
	where := " "
	if id > 0 {
		where = " where id<>" + strconv.Itoa(id)
	}
	query := "select id,operator_name from tbl_operator_info " + where
	err := meta.MerchantDB.Select(&data, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func GetOperatorMap() (map[string]string, error) {
	data := map[string]string{}
	list, _ := GetExtendMerchant(0)
	for _, val := range list {
		data[strconv.Itoa(val.Id)] = val.OperatorName
	}
	return data, nil
}

func ChannelConfigInsert(adminName, adminId string, data TblOperatorInfo) error {

	record := TblOperatorInfo{
		Id:                 helper.GenId(),
		OperatorName:       data.OperatorName,
		State:              data.State, //0未启用 1启用
		Password:           data.Password,
		ProxyExtendLink:    data.ProxyExtendLink,
		WithdrawFee:        data.WithdrawFee,
		RechargeFee:        data.RechargeFee,
		ApiFee:             "{}",
		SingleUrl:          data.SingleUrl,
		YoutubeShareLink:   data.YoutubeShareLink,
		TwitterShareLink:   data.TwitterShareLink,
		TelegramShareLink:  data.TelegramShareLink,
		InstagramShareLink: data.InstagramShareLink,
		CreatedAt:          time.Now().Unix(),
		CreatedUid:         adminId,
		CreatedName:        adminName,
		UpdatedAt:          time.Now().Unix(),
		UpdatedUid:         adminId,
		UpdatedName:        adminName,
	}
	tx, err := meta.MerchantDB.Begin()
	if err != nil {
		return pushLog(err, "数据库错误")
	}
	query, _, _ := dialect.Insert("tbl_operator_info").Rows(record).ToSQL()
	_, err = tx.Exec(query)
	if err != nil {
		_ = tx.Rollback()
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	err = tx.Commit()
	if err != nil {
		return pushLog(err, "数据库错误")
	}
	return err
}

func ChannelConfigUpdate(adminName, adminId string, data TblOperatorInfo) error {

	record := g.Record{
		"operator_name":        data.OperatorName,
		"state":                data.State, //0未启用 1启用
		"password":             data.Password,
		"proxy_extend_link":    data.ProxyExtendLink,
		"withdraw_remain":      data.WithdrawRemain,
		"withdraw_fee":         data.WithdrawFee,
		"recharge_fee":         data.RechargeFee,
		"api_fee":              data.ApiFee,
		"single_url":           data.SingleUrl,
		"youtube_share_link":   data.YoutubeShareLink,
		"twitter_share_link":   data.TwitterShareLink,
		"telegram_share_link":  data.TelegramShareLink,
		"instagram_share_link": data.InstagramShareLink,
		"updated_at":           time.Now().Unix(),
		"updated_uid":          adminId,
		"updated_name":         adminName,
	}
	query, _, _ := dialect.Update("tbl_operator_info").Set(&record).Where(g.Ex{"id": data.Id}).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

type ApiFee struct {
	GameId   string  `json:"game_id" db:"game_id"`
	GameName string  `json:"game_name" db:"game_name"`
	Rate     float64 `json:"rate" db:"rate"`
}

func MerchantUpdate(adminName, adminId string, data TblOperatorInfo) error {
	table := "tbl_operator_info"
	query := ""
	if data.Id != "" {
		OperatorInfo, _ := GetOperatorInfoById(data.Id)
		if data.Password == "" {
			data.Password = OperatorInfo.Password
		} else {
			v := fmt.Sprintf("%s", data.Password)
			enpwd, err := Encrypt(fmt.Sprintf("%s", v))
			if err != nil {
				return err
			}
			data.Password = enpwd
		}
		if data.Seamo == "unbind" {
			data.Seamo = ""
		} else {
			data.Seamo = OperatorInfo.Seamo
		}
		data.ApiFee = OperatorInfo.ApiFee
		data.UpdatedAt = time.Now().Unix()
		data.Id = data.Id

		query, _, _ = dialect.Update(table).Set(data).Where(g.Ex{"id": data.Id}).ToSQL()
		_, err := meta.MerchantDB.Exec(query)
		if err != nil {
			return errors.New("数据库错误")
		}
	} else {
		return MerchantAdd(adminName, adminId, data)
	}
	return nil
}

func MerchantAdd(adminName, adminId string, data TblOperatorInfo) error {
	table := "tbl_operator_info"
	query := ""
	proxyExtendLinkConfig := GameConfigByType(1)
	v := fmt.Sprintf("%s", data.Password)
	enpwd, err := Encrypt(fmt.Sprintf("%s", v))
	if err != nil {
		return err
	}
	data.Password = enpwd
	data.CreatedAt = time.Now().Unix()
	data.UpdatedUid = adminId
	data.CreatedUid = adminId
	data.CreatedName = adminName
	data.State = "1"

	data.UpdatedAt = time.Now().Unix()
	tx, err := meta.MerchantDB.Begin()
	data.Id = GetRandId(6)
	data.ProxyExtendLink = proxyExtendLinkConfig.CfgValue + data.Id
	query, _, _ = dialect.Insert(table).Rows(data).ToSQL()
	_, err = tx.Exec(query)
	if err != nil {
		tx.Rollback()
		fmt.Println(err)
		return errors.New("数据库错误")
	}
	quote := tblQuoteMangeTable{}
	quote.OperatorId, _ = strconv.Atoi(data.Id)
	query2, _, _ := dialect.Insert("tbl_operator_quota_manage").Rows(quote).ToSQL()
	_, err = tx.Exec(query2)
	if err != nil {
		tx.Rollback()
		fmt.Println(err)
		return errors.New("数据库错误")
	}
	//假pg rtp 同步888888
	query = fmt.Sprintf("UPDATE tbl_operator_info AS t1 JOIN (SELECT init_rtp,adjust_rtp,adjust_money_mul,into_fakepg_rate FROM tbl_operator_info WHERE id = 888888) AS t2 ON t1.id =%d SET t1.init_rtp = t2.init_rtp,t1.adjust_rtp = t2.adjust_rtp,t1.adjust_money_mul = t2.adjust_money_mul,t1.into_fakepg_rate = t2.into_fakepg_rate", quote.OperatorId)
	tx.Exec(query)

	query = fmt.Sprintf("insert into tbl_cfg_fakepg_rtp(money,RTP,operator_id) select money,RTP,%d from tbl_cfg_fakepg_rtp where operator_id=888888", quote.OperatorId)
	tx.Exec(query)

	//假pp rtp 同步888888
	query = fmt.Sprintf("UPDATE tbl_operator_info AS t1 JOIN (SELECT init_fakepp_rtp,adjust_fakepp_rtp,adjust_fakepp_money_mul,into_fakepp_rate FROM tbl_operator_info WHERE id = 888888) AS t2 ON t1.id =%d SET t1.init_fakepp_rtp = t2.init_fakepp_rtp,t1.adjust_fakepp_rtp = t2.adjust_fakepp_rtp,t1.adjust_fakepp_money_mul = t2.adjust_fakepp_money_mul,t1.into_fakepp_rate = t2.into_fakepp_rate", quote.OperatorId)
	tx.Exec(query)

	query = fmt.Sprintf("insert into tbl_cfg_fakepp_rtp(money,RTP,operator_id) select money,RTP,%d from tbl_cfg_fakepp_rtp where operator_id=888888", quote.OperatorId)
	tx.Exec(query)

	//新同步
	tx.Exec(fmt.Sprintf("insert into tbl_cfg_fake_rtp(money,rtp,game,operator_id) select money,rtp,game,%d from tbl_cfg_fake_rtp where operator_id=888888", quote.OperatorId))

	tx.Exec(fmt.Sprintf("insert into tbl_operator_info_fake(into_fake_rate,init_rtp,adjust_rtp,adjust_money_mul,game,operator_id) select into_fake_rate,init_rtp,adjust_rtp,adjust_money_mul,game,%d from tbl_operator_info_fake where operator_id=888888", quote.OperatorId))

	//掉绑配置同步 888888

	query = fmt.Sprintf("insert into tbl_cfg_disablebind(InviteCounts,DisableBindRate,max_disableBind,operator_id) select InviteCounts,DisableBindRate,max_disableBind,%d from tbl_cfg_disablebind where operator_id=888888", quote.OperatorId)
	tx.Exec(query)

	tx.Commit()
	return nil
}

func MerchantFakeUpdate(param TblFakeRtp, ctx *fasthttp.RequestCtx) error {
	tx, _ := meta.MerchantDB.Begin()
	OperatorInfoData, _ := GetMerchantList(1, 9999, "", "", ctx)

	if param.Game == "-1" {
		for _, v := range OperatorInfoData.D {
			if v.Id == "888888" {
				continue
			}
			tx.Exec(fmt.Sprintf("delete from tbl_cfg_fake_rtp where operator_id=%s", v.Id))
			tx.Exec(fmt.Sprintf("insert into tbl_cfg_fake_rtp(money,rtp,game,operator_id) select money,rtp,game,%s from tbl_cfg_fake_rtp where operator_id=888888", v.Id))

			tx.Exec(fmt.Sprintf("delete from tbl_operator_info_fake where operator_id=%s", v.Id))
			tx.Exec(fmt.Sprintf("insert into tbl_operator_info_fake(into_fake_rate,init_rtp,adjust_rtp,adjust_money_mul,game,operator_id) select into_fake_rate,init_rtp,adjust_rtp,adjust_money_mul,game,%s from tbl_operator_info_fake where operator_id=888888", v.Id))
		}

	} else {
		for _, v := range OperatorInfoData.D {
			if v.Id == "888888" {
				continue
			}
			tx.Exec(fmt.Sprintf("delete from tbl_cfg_fake_rtp where operator_id=%s and game="+param.Game, v.Id))
			tx.Exec(fmt.Sprintf("insert into tbl_cfg_fake_rtp(money,rtp,game,operator_id) select money,rtp,%s,%s from tbl_cfg_fake_rtp where operator_id=888888 and game="+param.Game, param.Game, v.Id))

			tx.Exec(fmt.Sprintf("delete from tbl_operator_info_fake where operator_id=%s and game="+param.Game, v.Id))
			tx.Exec(fmt.Sprintf("insert into tbl_operator_info_fake(into_fake_rate,init_rtp,adjust_rtp,adjust_money_mul,game,operator_id) select into_fake_rate,init_rtp,adjust_rtp,adjust_money_mul,%s,%s from tbl_operator_info_fake where operator_id=888888 and game="+param.Game, param.Game, v.Id))
		}
	}

	tx.Commit()

	return nil
}

func MerchantUpdateOfficial(ctx *fasthttp.RequestCtx) error {
	tx, _ := meta.MerchantDB.Begin()
	tx.Exec(fmt.Sprintf("UPDATE tbl_operator_info AS t1 JOIN (SELECT init_rtp,adjust_rtp,adjust_money_mul,into_fakepg_rate FROM tbl_operator_info WHERE id = 888888) AS t2 ON t1.id<>888888 SET t1.init_rtp = t2.init_rtp,t1.adjust_rtp = t2.adjust_rtp,t1.adjust_money_mul = t2.adjust_money_mul,t1.into_fakepg_rate = t2.into_fakepg_rate"))
	tx.Exec(fmt.Sprintf("delete from tbl_cfg_fakepg_rtp where operator_id<>888888"))
	OperatorInfoData, _ := GetMerchantList(1, 9999, "", "", ctx)

	for _, v := range OperatorInfoData.D {
		if v.Id == "888888" {
			continue
		}
		tx.Exec(fmt.Sprintf("insert into tbl_cfg_fakepg_rtp(money,RTP,operator_id) select money,RTP,%s from tbl_cfg_fakepg_rtp where operator_id=888888", v.Id))
	}

	tx.Commit()

	return nil
}

func MerchantUpdateOfficialPP(ctx *fasthttp.RequestCtx) error {
	tx, _ := meta.MerchantDB.Begin()
	tx.Exec(fmt.Sprintf("UPDATE tbl_operator_info AS t1 JOIN (SELECT init_fakepp_rtp,adjust_fakepp_rtp,adjust_fakepp_money_mul,into_fakepp_rate FROM tbl_operator_info WHERE id = 888888) AS t2 ON t1.id<>888888 SET t1.init_fakepp_rtp = t2.init_fakepp_rtp,t1.adjust_fakepp_rtp = t2.adjust_fakepp_rtp,t1.adjust_fakepp_money_mul = t2.adjust_fakepp_money_mul,t1.into_fakepp_rate = t2.into_fakepp_rate"))
	tx.Exec(fmt.Sprintf("delete from tbl_cfg_fakepp_rtp where operator_id<>888888"))
	OperatorInfoData, _ := GetMerchantList(1, 9999, "", "", ctx)

	for _, v := range OperatorInfoData.D {
		if v.Id == "888888" {
			continue
		}
		tx.Exec(fmt.Sprintf("insert into tbl_cfg_fakepp_rtp(money,RTP,operator_id) select money,RTP,%s from tbl_cfg_fakepp_rtp where operator_id=888888", v.Id))
	}

	tx.Commit()

	return nil
}

func MerchantUpdateOfficial2(ctx *fasthttp.RequestCtx) error {
	tx, _ := meta.MerchantDB.Begin()

	tx.Exec(fmt.Sprintf("delete from tbl_cfg_disablebind where operator_id<>888888"))
	OperatorInfoData, _ := GetMerchantList(1, 9999, "", "", ctx)

	for _, v := range OperatorInfoData.D {
		if v.Id == "888888" {
			continue
		}
		tx.Exec(fmt.Sprintf("insert into tbl_cfg_disablebind(InviteCounts,DisableBindRate,max_disableBind,operator_id) select InviteCounts,DisableBindRate,max_disableBind,%s from tbl_cfg_disablebind where operator_id=888888", v.Id))
	}

	tx.Commit()

	return nil
}

func ChannelApifeeUpdate(adminName, adminId string, data TblOperatorInfo) error {

	record := g.Record{
		"api_fee":      data.ApiFee,
		"updated_at":   time.Now().Unix(),
		"updated_uid":  adminId,
		"updated_name": adminName,
	}
	query, _, _ := dialect.Update("tbl_operator_info").Set(&record).Where(g.Ex{"id": data.Id}).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func GetOperatorInfoByUsername(username string) (TblOperatorInfo, error) {
	data := TblOperatorInfo{}
	t := dialect.From("tbl_operator_info")
	query, _, _ := t.Select(colsOperatorInfo...).Where(g.Ex{"operator_name": username}).Limit(1).ToSQL()

	err := meta.MerchantDB.Get(&data, query)
	// 账号不存在提示
	if err == sql.ErrNoRows {
		return data, errors.New(helper.UserNotExist)
	}
	return data, nil
}

type OperatorInfo struct {
	Id           string `json:"id" db:"id"`
	OperatorName string `json:"operator_name" db:"operator_name"` // 渠道名称
}

func GetOperatorInfoName(username string) OperatorInfo {
	data := OperatorInfo{}
	t := dialect.From("tbl_operator_info")
	query, _, _ := t.Select("id", "operator_name").Where(g.Ex{"operator_name": username}).Limit(1).ToSQL()

	meta.MerchantDB.Get(&data, query)
	return data
}

func GetOperatorInfoById(id string) (TblOperatorInfo, error) {
	data := TblOperatorInfo{}
	t := dialect.From("tbl_operator_info")
	query, _, _ := t.Select(colsOperatorInfo...).Where(g.Ex{"id": id}).Limit(1).ToSQL()

	err := meta.MerchantDB.Get(&data, query)
	// 账号不存在提示
	if err == sql.ErrNoRows {
		return data, errors.New(helper.UserNotExist)
	}
	return data, nil
}

func UpdateOperatorPassword(id string, password string) error {
	record := g.Record{
		"password": password,
	}
	query := ""
	if id == "" {
		query, _, _ = dialect.Update("tbl_operator_info").Set(record).ToSQL()
	} else {
		query, _, _ = dialect.Update("tbl_operator_info").Set(record).Where(g.Ex{"id": id}).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		body := fmt.Errorf("%s,[%s]", err.Error(), query)
		return pushLog(body, "数据库错误")
	}
	return nil
}

func UpdateOnekeyToFakepg(rate int) error {
	record := g.Record{
		"into_fakepg_rate": rate,
	}
	query, _, _ := dialect.Update("tbl_operator_info").Set(record).ToSQL()
	fmt.Println(query)
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		body := fmt.Errorf("%s,[%s]", err.Error(), query)
		return pushLog(body, "数据库错误")
	}
	return nil
}

func UpdateOperatorGoogleSecret(id string, seamo string) error {
	record := g.Record{
		"seamo": seamo,
	}
	query, _, _ := dialect.Update("tbl_operator_info").Set(record).Where(g.Ex{"id": id}).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		body := fmt.Errorf("%s,[%s]", err.Error(), query)
		return pushLog(body, "数据库错误")
	}
	return nil
}

type ChannelWagedParam struct {
	Id          int    `json:"id"`
	ChannelId   int    `json:"channel_id"`
	ChannelName string `json:"channel_name"`
	Ty          int    `json:"ty"`
	TyName      string `json:"ty_name"`
	Page        int    `json:"page"`
	PageSize    int    `json:"page_size"`
}
type ChannelWaged struct {
	ChannelId       int     `json:"channel_id" db:"channel_id"`
	Ty              int     `json:"ty" db:"ty"`
	TyName          string  `json:"name" db:"name"`
	FlowMultiple    float64 `json:"channel_flow_multiple" db:"channel_flow_multiple"`
	DefaultMultiple float64 `json:"default_flow_multiple" db:"default_flow_multiple"`
}

type ChannelWagedTable struct {
	ChannelId    int     `json:"channel_id" db:"channel_id"`
	Ty           int     `json:"ty" db:"ty"`
	FlowMultiple float64 `json:"flow_multiple" db:"flow_multiple"`
}

type ChannelWagedRetData struct {
	T int            `cbor:"t" json:"total"`
	D []ChannelWaged `cbor:"d" json:"d"`
}

func GetChannelWagedList(param ChannelWagedParam) (ChannelWagedRetData, error) {
	data := ChannelWagedRetData{}
	query := fmt.Sprintf("SELECT  o.id AS channel_id,"+
		"	cfg.ty,"+
		"	cfg.name,"+
		"	COALESCE(w.flow_multiple, -1) AS channel_flow_multiple, "+
		"	cfg.flow_multiple AS default_flow_multiple"+
		"	FROM tbl_operator_info AS o"+
		"	JOIN tbl_flow_config AS cfg"+
		"   ON cfg.ty IN (100,103)"+
		"	LEFT JOIN tbl_cfg_channel_waged AS w"+
		"	ON w.channel_id = o.id"+
		"	AND w.ty = cfg.ty"+
		"	WHERE o.id = %d;", param.ChannelId)
	err := meta.MerchantDB.Select(&data.D, query)
	if len(data.D) > 0 {
		data.T = 1
	}

	helper.InfoLog("GetChannelWagedList:%s", query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

/*
func GetChannelWagedList(param ChannelWagedParam) (ChannelWagedRetData, error) {

		data := ChannelWagedRetData{}

		where := "1=1"
		table := "tbl_cfg_channel_waged"
		join := ""
		oderBy := "a.id"
		oderType := "desc"

		if param.ChannelId != 0 {
			where += " and a.channel_id='" + strconv.Itoa(param.ChannelId) + "'"
		}
		if param.ChannelName != "" {
			where += " and c.ChannelName like '%" + param.ChannelName + "%'"
		}
		if param.Ty != 0 {
			where += " and a.ty='" + strconv.Itoa(param.Ty) + "'"
		}
		if param.TyName != "" {
			where += " and b.name like '%" + param.TyName + "%'"
		}
		join += " left join tbl_flow_config as b on a.ty=b.ty"
		join += " left join tbl_operator_info as c on c.id=a.channel_id" //渠道表

		order := oderBy + " " + oderType
		offset := (param.Page - 1) * param.PageSize
		if param.Page >= 1 {
			count := "select count(1) from " + table + " as a " + join + " where " + where

			err := meta.MerchantDB.Get(&data.T, count)
			if err != nil {

				return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
			}

			if data.T == 0 {
				return data, nil
			}
		}
		field := "a.*,ifnull(b.name,'') as ty_name,ifnull(c.operator_name,'') as channel_name"
		query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
		err := meta.MerchantDB.Select(&data.D, query)
		if err != nil && err != sql.ErrNoRows {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}
		return data, nil
	}
*/
func UpdateChannelWaged(param ChannelWagedTable, isDelete int) error {
	table := "tbl_cfg_channel_waged"
	query := ""

	autoId := 0
	meta.MerchantDB.Get(&autoId, fmt.Sprintf("select id from tbl_cfg_channel_waged where channel_id='%d' and ty='%d'", param.ChannelId, param.Ty))
	if autoId > 0 {
		ut := g.Record{
			"flow_multiple": param.FlowMultiple,
		}
		query, _, _ = dialect.Update(table).Set(ut).Where(g.Ex{"channel_id": param.ChannelId, "ty": param.Ty}).ToSQL()
	} else {
		ut := g.Record{
			"channel_id":    param.ChannelId,
			"ty":            param.Ty,
			"flow_multiple": param.FlowMultiple,
		}
		query, _, _ = dialect.Insert(table).Rows(ut).ToSQL()
	}

	helper.InfoLog("UpdateChannelWaged:%s", query)
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}
